<template>
	<view :data-theme="themeStyle" class="detail">
		<view scroll-y="true">
			<LeftSide @tryPlay="tryPlay"></LeftSide>
			<RightSide @goBoxList="goBoxList" @goMoney="goMoney"></RightSide>
			<view class="bg">
				<download-tip id="app-download-link" @closeDownload="closeDownload"></download-tip>
				<Nav title="魔力福袋" @back="back" :bgColor="bgColor" :top="navTop"></Nav>
				<Banner :detailData="detailData" :barrageData="boxMsgList" @changePopType="changePopType"></Banner>
			</view>
			<CardsSwiper @openPop="openPop" :list="detailData.manyGoods" :config="configData" :autoplay="autoplay">
			</CardsSwiper>
			<More :magicBoxInfo="magicBoxInfo" @goDetail="goDetail"></More>
			<BottomButton v-if="detailData.id" @goBuy="goBuy" :detailData="detailData"></BottomButton>
			<uni-popup class="pop" ref="popup" type="bottom">
				<all-goods v-if="type=='allGoods'" @closePop="closePop" v-on="$listeners" @changePopType="changePopType"
					:rateList="rateList" :goodList="detailData.manyGoods"></all-goods>
				<shop-detail v-else-if="type=='detail'" @closePop="closePop" :value="shopDetailValue">></shop-detail>
				<confirm-pay v-else-if="type=='confirmPay'" @closePop="closePop" @confirm="confirmToPay"
					:zfData="detailData" :payType="payType"></confirm-pay>
			</uni-popup>
			<to-top v-if="showTop" @toTop="scrollToTopNative()"></to-top>
			<ns-login ref="login"></ns-login>
			<full-loading :loadshow="loadshow"></full-loading>
		</view>
	</view>
</template>

<script>
	import globalConfig from '@/common/js/golbalConfig.js';
	import scroll from '@/common/js/scroll-view.js';
	import Banner from "./components/Banner.vue";
	import LeftSide from "./components/LeftSide.vue";
	import RightSide from "./components/RightSide.vue";
	import CardsSwiper from "./components/CardSwiper.vue";
	import BottomButton from "./components/BottomButton.vue";
	import More from './components/More.vue';
	import AllGoods from './components/AllGoods.vue';
	import ShopDetail from '@/components/magic-box/shop-detail/index.vue';
	import ConfirmPay from './components/ConfirmPay.vue';
	import toTop from '@/components/toTop/toTop.vue';
	import Nav from "@/components/magic-box/magic-nav/index.vue";
	import navMixin from "@/common/js/nav.js"
	import pageApi from "@/common/js/pageApi.js";

	export default {
		components: {
			Banner,
			LeftSide,
			RightSide,
			CardsSwiper,
			BottomButton,
			More,
			toTop,
			AllGoods,
			ShopDetail,
			ConfirmPay,
			Nav
		},
		computed: {
			userInfo() {
				return this.$store.state.userInfo || {};
			},
			isLogin() {
				return this.$store.state.isLogin || false;
			},
			isOpenCustomerPay() {
				return this.$store.state.isOpenCustomerPay || false;
			}
		},
		data() {
			return {
				configData: { // 配置一页放多少条数据
					multiple: 5,
				},
				detailData: {}, // 详情数据
				type: 'detail',
				fromType: '', // 打开弹窗的方式
				payType: '', // 支付类型 1发/5发
				shopDetailValue: {
					sku_id: "",
					content: ""
				},
				magicBoxInfo: { // 更多推荐
					params: {
						page: 0,
						page_num: 5,
						display: []
					},
					list: [],
					finish: false,
					loading: false,
				},
				boxMsgList: [], // 消息列表
				rateList: [], // 概率列表
				boxId: '', // 福袋Id
				navTop: '0px',
				loadshow: false,
				bottomButtonLoading: false,
				autoplay: true,
				couponId: 0
			}
		},
		mixins: [scroll, globalConfig, navMixin, pageApi],
		onLoad(option) {
			this.loadshow = true;
			this.boxId = option.magicBoxId;
			this.couponId = option.coupon_id;
			this.getBoxDetail();
		},
		onShow() {
			this.autoplay = true;
			if (this.isLogin) {
				this.$store.dispatch("getUserInfo");
				console.log('couponId', this.couponId)
			}
			console.log('isOpenCustomerPay', this.isOpenCustomerPay)
		},
		onUnload() {
			console.log('onUnload')
		},
		onHide() {
			this.loadshow = false;
			this.autoplay = false;
		},
		onReady() {
			this.computedNavTop();
		},
		onReachBottom() {
			this.getMagicBoxList();
		},
		methods: {
			// 关闭下载tip,重新计算高度
			closeDownload() {
				const res = uni.getSystemInfoSync();
				this.navTop = res.statusBarHeight + 'px';
				// console.log('重新计算高度',this.navTop);
			},
			computedNavTop() {
				const res = uni.getSystemInfoSync();
				// console.log('状态栏高度', res.statusBarHeight);
				this.navTop = res.statusBarHeight + 'px';
				// #ifdef H5
				const query = uni.createSelectorQuery().in(this);
				query.select('#app-download-link').boundingClientRect(data => {
					// console.log("得到布局位置信息", data);
					if (data) {
						this.navTop = data.height + res.statusBarHeight + 'px';
					}
				}).exec();
				// #endif
			},
			getMagicBoxList() {
				let displayArr = this.magicBoxInfo.list.map(item => item.id);
				if (this.detailData.id) {
					displayArr.unshift(this.detailData.id);
				}
				this.magicBoxInfo.params.display = displayArr.join(",");
				this.api(this.magicBoxInfo, "/api/fudai/boxlist")
			},
			// 获取福袋详情
			async getBoxDetail() {
				const params = {
					fid: this.boxId,
				};
				if (this.couponId) {
					params.box_coupon_id = this.couponId
				}
				const res = await this.$api.sendRequest({
					url: "/api/fudai/detail",
					data: params,
					async: false
				});
				this.loadshow = false;
				if (res.code >= 0) {
					this.detailData = res.data.detail;
					this.rateList = res.data.rate;
					// 统计福袋ID
					// console.log('this.detailData.id',this.detailData.id)
					uni.report('see_luckybag', `${this.detailData.id||'-'}`)
					this.getOpenMsgList();
					this.getMagicBoxList();
				} else if (res.code == -101) {
					uni.showModal({
						title: '温馨提示',
						content: '该福袋已下架，请到其它福袋逛逛哦！',
						showCancel: false,
						success: () => {
							uni.navigateBack({
								delta: 1
							})
						}

					})
				} else if (res.code == -102) {
					uni.showModal({
						title: '温馨提示',
						content: '该福袋已删除，请到其它福袋逛逛哦！',
						showCancel: false,
						success: () => {
							uni.navigateBack({
								delta: 1
							})
						}
					})
				} else {
					this.$util.showToast({
						title: res.message
					});
				}
			},
			// 获取开盒消息
			async getOpenMsgList() {
				const res = await this.$store.dispatch('getOpenMsgList', {
					type: 1,
					fid: this.boxId
				});
				this.boxMsgList = res;
			},
			// 去盒柜列表
			goBoxList() {
				if (!this.isLogin) {
					this.$util.redirectTo("/otherpages/login/login/login", {
						back: '/pages/magic-box/detail/detail?magicBoxId=' + this.boxId
					})
					return;
				}
				this.$util.redirectTo('/magicpages/magic/box_ark');
			},
			goMoney() {
				if (!this.isLogin) {
					this.$util.redirectTo("/otherpages/login/login/login", {
						back: '/pages/magic-box/detail/detail?magicBoxId=' + this.boxId
					})
					return;
				}
				this.$util.redirectTo('/magicpages/coin_record/coin_record');
			},
			// 试玩
			async tryPlay() {
				this.$store.dispatch('getOpenMagicBox', {
					fid: this.boxId,
					tryDo: 1
				});
				this.$util.redirectTo('/pages/magic-box/draw/index', {
					try: '1'
				});
			},
			// 去支付
			async goBuy({
				type
			}) {
				if (!this.isLogin) {
					this.$util.redirectTo("/otherpages/login/login/login", {
						back: '/pages/magic-box/detail/detail?magicBoxId=' + this.boxId
					})
					return;
				}
				// 防止重复请求接口
				if (this.bottomButtonLoading) {
					return;
				}
				// console.log('type', type);
				// console.log('一发价格', this.detailData.price);
				this.bottomButtonLoading = true;
				let url = '/api/fudai/boxprice';
				let params = {
					fid: this.boxId,
					price: this.detailData.price,
				}
				const res = await this.$api.sendRequest({
					url: url,
					data: params,
					async: false,
				});
				this.bottomButtonLoading = false;
				if (res.data.price) {
					uni.showModal({
						title: '温馨提示',
						content: "福袋价格已经更新",
						showCancel: false,
						success: () => {
							this.loadshow = true;
							this.getBoxDetail();
						}
					})
					return
				}
				this.payType = type;
				this.openPop({
					type: 'confirmPay',
					fromType: 'buy'
				});
				this.$refs.popup.open();
			},
			changePopType({
				type,
				value = {},
				openPop = false,
				fromType,
			}) {
				// console.log('fromType',fromType)
				this.type = type;
				this.fromType = fromType;
				if (openPop) {
					this.$refs.popup.open();
				}
				this.shopDetailValue = {
					sku_id: value.sku_id,
					content: value.goods_content,
				};
			},
			openPop({
				type,
				fromType
			}) {
				// console.log('fromType',fromType);
				this.type = type;
				this.fromType = fromType;
				this.$refs.popup.open();
			},
			closePop() {
				// console.log('fromType',this.fromType);
				if (this.fromType == 'good') {
					this.fromType = 'card';
					this.type = 'allGoods';
				} else {
					this.$refs.popup.close();
					this.fromType = '';
				}
			},
			// 确认支付
			async confirmToPay() {
				let allPrice = 0;
				if (this.detailData.box_coupon_id) {
					allPrice = this.detailData.newprice;
				} else {
					allPrice = this.detailData.price * Number(this.payType);
				}
				if (Number(allPrice) > Number(this.userInfo.coin)) {
					// uni.showModal({
					// 	title: '提示',
					// 	content: '余额不足！',
					// 	confirmText: '去充值',
					// 	success: (res) => {
					// 		if (res.confirm) {
					// 			this.$util.redirectTo('/magicpages/rest_charge/rest_charge', {
					// 				payCount: allPrice,
					// 				box_id: this.boxId,
					// 				box_way: this.payType
					// 			});
					// 		} else if (res.cancel) {}
					// 	}
					// });
					if (this.isOpenCustomerPay) {
						this.$util.redirectTo('/magicpages/rest_charge/rest_charge', {
							payCount: allPrice,
							box_id: this.boxId,
							box_way: this.payType,
						}, "redirectTo");
					} else {
						this.$util.redirectTo('/magicpages/account_charge/account_charge', {
							box_id: this.boxId,
						}, "redirectTo");
						// this.$util.redirectTo('/magicpages/rest_charge/rest_charge', {
						// 	payCount: allPrice,
						// 	box_id: this.boxId,
						// 	box_way: this.payType,
						// }, "redirectTo");
					}
					return;
				}
				// 余额充足
				let url = '/api/coin/boxbuy';
				let params = {
					box_id: this.boxId,
					box_way: this.payType,
				}
				if (this.detailData.box_coupon_id) {
					params.box_coupon_id = this.detailData.box_coupon_id;
				}
				const res = await this.$api.sendRequest({
					url: url,
					data: params,
					async: false,
				});
				if (res.code >= 0) {
					this.closePop();
					this.$store.dispatch("getUserInfo");
					this.openMagicBox(res.data);
				} else {
					this.$util.showToast({
						title: res.message
					});
				}
			},
			// 支付成功，开福袋
			async openMagicBox({
				out_trade_no
			}) {
				this.$store.dispatch('getOpenMagicBox', {
					fid: this.boxId,
					box_way: this.payType,
					out_trade_no,
				});
				// 有免费福袋抵扣
				if (this.detailData.box_coupon_id > 0) {
					this.$store.commit('setIsFreeListRefresh', true);
					this.$util.redirectTo('/pages/magic-box/draw/index', {}, "redirectTo");
				} else {
					this.$util.redirectTo('/pages/magic-box/draw/index');
				}

				// const res = await this.$api.sendRequest({
				// 	url: '/api/fudai/open',
				// 	data: {
				// 		fid: this.boxId,
				// 		box_way: this.payType,
				// 		out_trade_no,
				// 	},
				// 	async: false,
				// });
				// if (res.code >= 0) {
				// 	uni.setStorageSync('openMagicBox', res.data);
				// 	this.$util.redirectTo('/pages/magic-box/draw/index');
				// } else {
				// 	this.$util.showToast({
				// 		title: res.message
				// 	});
				// }
			},
			// 去盲盒详情
			goDetail({
				id
			}) {
				this.loadshow = true;
				setTimeout(() => {
					this.loadshow = false;
				}, 2000)
				this.$util.redirectTo('/pages/magic-box/detail/detail', {
					magicBoxId: id
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import '@/common/css/main.scss';

	.detail /deep/ .mescroll-totop {
		bottom: 152rpx !important;
	}

	.detail {
		background: #E9EBF9;
		display: flex;
		flex-direction: column;
		flex: 1;
		padding-bottom: 132rpx;

		.pop {
			/deep/ .uni-popup__wrapper.uni-custom {
				border-top-left-radius: 45rpx;
				border-top-right-radius: 45rpx;

				.uni-popup__wrapper-box {
					border-top-left-radius: 45rpx;
					border-top-right-radius: 45rpx;
					max-height: 1800px;
				}
			}
		}

	}

	.bg {
		background: url(@/static/image/detail-bg.png);
		background-size: 100% 100%;
	}
</style>
